package com.zyd.shiro.business.controller.pak;



import com.zyd.shiro.framework.object.ResponseVO;
import com.zyd.shiro.util.ResultUtil;
import com.zyd.shiro.utils.FileUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;

@RestController
@RequestMapping("/file")
public class FileController {

    @Value("${server.url}")
    private String url;


    @PostMapping(value = "/upload")
    public ResponseVO folderImport(@RequestParam(value = "file") MultipartFile file) {
        if (file == null) {
            return ResultUtil.error("请上传文件！");
        }
        try {
            String path = file.getOriginalFilename();
            String name = path.substring(path.lastIndexOf("/") + 1, path.length());
            File newFile = new File(FileUtils.createFilePath(name));
            file.transferTo(newFile);
            String link = url+"/upload/" + name;
            return ResultUtil.success("上传成功！", link);
        } catch (Exception e) {
            return ResultUtil.error(e.getMessage());
        }
    }

    @RequestMapping("/download")
    public void download(String path, HttpServletResponse response) throws IOException {
        // 读到流中
        InputStream inputStream = new FileInputStream(path);// 文件的存放路径
        response.reset();
        response.setContentType("application/octet-stream");
        String filename = new File(path).getName();
        response.addHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(filename, "UTF-8"));
        ServletOutputStream outputStream = response.getOutputStream();
        byte[] b = new byte[1024];
        int len;
        //从输入流中读取一定数量的字节，并将其存储在缓冲区字节数组中，读到末尾返回-1
        while ((len = inputStream.read(b)) > 0) {
            outputStream.write(b, 0, len);
        }
        inputStream.close();
    }





}
